import { getRestaurantTables } from '@/services/ant-design-pro/desk';
import { getUserByMobile, getUserDetail, getUserList } from '@/services/ant-design-pro/menber';
import { getProductList } from '@/services/ant-design-pro/product';
import {
  bindTradeUser,
  cancelTrade,
  checkoutPreview,
  getTradeDetail,
  modifyTrade,
  printCashierTicket,
  printOrderTicket,
  printTradeTicket,
} from '@/services/order';
import { useDebounceFn } from '@ant-design/pro-components';
import {
  AutoComplete,
  Button,
  Card,
  Col,
  Divider,
  Empty,
  Form,
  InputNumber,
  message,
  Modal,
  Popconfirm,
  Row,
  Select,
  Spin,
  Switch,
  Table,
} from 'antd';
import { useEffect, useState } from 'react';
import AddOrderProductModal from '../AddOrderProductModal';
import OrderStatusTag from '../OrderStatus';

const makeTradeOrderList = (orders) => {
  return orders.map((order) => {
    return {
      orderId: order?.id,
      productId: order?.item?.productId,
      variantId: order?.item?.variantId,
      quantity: order?.item?.quantity,
    };
  });
};

const EditableCell: React.FC<React.PropsWithChildren<EditableCellProps>> = ({
  editing,
  dataIndex,
  children,
  ...restProps
}) => {
  return (
    <td {...restProps}>
      {editing ? (
        <Form.Item
          name={'quantity'}
          style={{ margin: 0 }}
          rules={[
            {
              required: true,
              message: `请输入`,
            },
          ]}
        >
          <InputNumber />
        </Form.Item>
      ) : (
        children
      )}
    </td>
  );
};

const OrderDetailModal = ({ name = '订单详情', orderId = null, onCancel = () => { } }) => {
  const [open, setOpen] = useState(false);
  const [checkoutModalOpen, setCheckoutModalOpen] = useState(false);
  const [editOpen, setEditOpen] = useState(false);
  const [singleEditOpen, setSingleEditOpen] = useState(false);
  const [orderProductOpen, setOrderProductOpen] = useState(false);
  const [tradeDetail, setTradeDetail] = useState({});
  const [editParams, setEditParams] = useState({});
  const [singEditParams, setSingleEditParams] = useState({});
  const [productList, setProductList] = useState([]);
  const [tableList, setTableList] = useState([]);
  const [checkoutUser, setCheckoutUser] = useState(null);
  const [menberInputVal, setMenberInputVal] = useState(null);
  const [checkoutDetail, setCheckoutDetail] = useState(null);
  const [checkoutBindedUser, setCheckoutbindedUser] = useState(null);

  const [productListForm] = Form.useForm();
  const [editingKey, setEditingKey] = useState('');
  const [editingOrderId, setEditingOrderId] = useState(null);
  const [userOptions, setUserOptions] = useState([]);
  const [loading, setLoading] = useState(false);

  const [editOrderForm] = Form.useForm();
  const [editSingleOrderForm] = Form.useForm();
  const [menberForm] = Form.useForm();

  const init = async ({ addOrderNum = null } = {}) => {
    setLoading(true);
    const resp = await getTradeDetail(orderId);
    const { data } = resp;
    setTradeDetail(data);
    setLoading(false);

    if (addOrderNum) {
      const orders = resp?.data?.orders;
      console.log('[orders]', orders);
      const addOrderList = orders?.slice(orders?.length - addOrderNum);
      console.log('[addOrderList]', addOrderList);
      const allPrint = addOrderList.map((item) => {
        return printOrderTicket(item.id);
      });

      await Promise.all(allPrint);
    }
  };

  const handleEditOrder = async (
    tradeOrderList = makeTradeOrderList(tradeDetail?.orders),
    addOrderNum = null,
  ) => {
    setLoading(true);
    console.log('[tradeDetail]', tradeDetail);

    const params = {
      id: orderId,
      tableId: tradeDetail?.restaurantTable?.id,
      tradeOrderList,
      ...editParams,
    };
    if (!tradeDetail?.restaurantTable?.id) {
      message.error('桌号有误，请刷新重试');
      return;
    }
    console.log(tradeOrderList);
    const resp = await modifyTrade(params);

    if (resp.code === 0) {
      message.success('操作成功');

      setOrderProductOpen(false);

      init({ addOrderNum });
    }

    setLoading(false);
  };

  const editOrderProductList = (record: Partial<DataType> & { key: React.Key }, id) => {
    const list = makeTradeOrderList(tradeDetail?.orders);
    const order = list.find((item) => item.orderId === id);
    productListForm.setFieldsValue(order);
    const vals = productListForm.getFieldsValue();
    console.log('[order]', order);
    setEditingKey(record.quantity);
    setEditingOrderId(id);
  };

  const saveOrderProductList = async (key: React.Key) => {
    try {
      const row = (await productListForm.validateFields()) as DataType;
      const newData = makeTradeOrderList(tradeDetail?.orders);
      const index = newData.findIndex((item) => editingOrderId === item.orderId);
      if (index > -1) {
        const item = newData[index];
        newData.splice(index, 1, {
          ...item,
          ...row,
        });
        console.log('[newData]', newData);
        handleEditOrder(newData);
        setEditingKey('');
      } else {
        newData.push(row);
        setEditingKey('');
      }
    } catch (errInfo) {
      console.log('Validate Failed:', errInfo);
    }
  };

  const initProductList = async (params = {}) => {
    const resp = await getProductList({ ...params, status: 1 });

    const { list } = resp?.data;

    setProductList(list);
  };
  const initTable = async (areaId = undefined) => {
    const resp = await getRestaurantTables({ areaId });

    const { list } = resp?.data;
    setTableList(list);
  };

  useEffect(() => {
    if (orderId) {
      setOpen(true);
      init();
      initProductList();
      initTable();
    }
  }, [orderId]);

  const isEditing = (record) => record.key === editingKey;

  const ProductShowColumns = [
    {
      title: '产品名称',
      dataIndex: 'item',
      key: 'item',
      render: (_) => {
        return _.productName;
      },
    },
    {
      title: 'SKU',
      dataIndex: 'item',
      key: 'item',
      render: (_) => {
        return _.variantName || '无';
      },
    },
    {
      width: '135px',
      title: '价格',
      dataIndex: 'payment',
      key: 'payment',
      render: (_) => {
        console.log('[_]', _);
        return (
          <>
            <Row justify="space-between">
              <Col>原价：</Col>
              <Col>￥{_?.originAmount}</Col>
            </Row>
            <Row justify="space-between">
              <Col>调整：</Col>
              <Col>￥{_?.adjust}</Col>
            </Row>
            <Row justify="space-between">
              <Col>折扣：</Col>
              <Col>￥{_?.discount}</Col>
            </Row>
            <Row justify="space-between red">
              <Col>实际支付：</Col>
              <Col>￥{_?.amount}</Col>
            </Row>
          </>
        );
      },
    },
    {
      title: '数量',
      dataIndex: 'quantity',
      key: 'quantity',
      editable: true,
      render: (_, record) => {
        return record?.item?.quantity;
      },
    },
    ...[
      tradeDetail?.status == 1
        ? {
          title: '操作',
          dataIndex: 'option',
          valueType: 'option',
          width: '200px',
          render: (_, record) => {
            const editable = isEditing(record);

            return (
              <Row gutter={[10, 10]} className="flex-wrap">
                <Col>
                  <Button
                    size="small"
                    onClick={() => {
                      setSingleEditOpen(true);
                      setSingleEditParams({
                        orderId: record?.id,
                        ...record?.item,
                        price: record?.payment?.totalAmount,
                      });
                      editSingleOrderForm.setFieldsValue({
                        totalAmount: record?.item?.totalAmount,
                      });
                    }}
                    type="primary"
                  >
                    折扣
                  </Button>
                </Col>
                <Col>
                  {editable ? (
                    <span>
                      <Button
                        type="primary"
                        size="small"
                        onClick={() => saveOrderProductList(record.key)}
                      >
                        保存
                      </Button>
                      <Popconfirm
                        title="确认取消吗?"
                        onConfirm={() => {
                          setEditingKey('');
                        }}
                      >
                        <Button danger type="primary" size="small" className="ml10">
                          取消
                        </Button>
                      </Popconfirm>
                    </span>
                  ) : (
                    <Button
                      size="small"
                      onClick={() => {
                        editOrderProductList(record, record?.id);
                      }}
                      type="primary"
                    >
                      编辑
                    </Button>
                  )}
                </Col>
                <Col>
                  <Popconfirm
                    title="确认删除吗"
                    key="delete"
                    onConfirm={async () => {
                      const tradeOrderList = makeTradeOrderList(tradeDetail?.orders).filter(
                        (item) => item.orderId !== record.id,
                      );
                      handleEditOrder(tradeOrderList);
                    }}
                  >
                    <Button size="small" type="primary" danger>
                      删除
                    </Button>
                  </Popconfirm>
                </Col>
              </Row>
            );
          },
        }
        : [],
    ],
  ];

  const mergedColumns = ProductShowColumns.map((col) => {
    if (!col.editable) {
      return col;
    }
    return {
      ...col,
      onCell: (record) => ({
        record,
        inputType: col.dataIndex === 'age' ? 'number' : 'text',
        dataIndex: col.dataIndex,
        title: col.title,
        editing: isEditing(record),
      }),
    };
  });

  const handlePreviewCheckout = async (_, vals) => {
    console.log('[vals]', vals);
    console.log('handlePreviewCheckout');
    const resp = await checkoutPreview(orderId, {
      action: 'preview',
      ...vals,
      payMethod: 'cash',
    });
    console.log('[resp]', resp);
    setCheckoutDetail(resp?.data);
  };

  const handleCheckout = async () => {
    const resp = await checkoutPreview(orderId, {
      action: 'pay',
      ...menberForm.getFieldsValue(),
      payMethod: 'cash',
    });

    if (resp.code === 0) {
      message.success('操作成功');

      init();
      setCheckoutModalOpen(false);

      if (localStorage.getItem('disableCheckoutPrint') !== 'true') {
        const resp = await printCashierTicket(orderId);
        if (resp.code === 0) {
          message.success('打印成功');
        }
      }
    }
  };

  const searchMenber = async (userMobile) => {
    const resp = await getUserByMobile({ mobile: userMobile });

    if (resp.code === 0) {
      setCheckoutUser(resp?.data);
    }
  };

  const getMenber = async (id) => {
    const resp = await getUserDetail(id);

    if (resp.code === 0) {
      setMenberInputVal(resp?.data?.username);

      setCheckoutUser(resp?.data);
    }
  };

  const bindMenber = async () => {
    const resp = await bindTradeUser(orderId, { userId: checkoutUser?.id });

    if (resp.code === 0) {
      message.success('绑定成功');
      setCheckoutbindedUser({
        status: 1,
      });
    }
  };

  const { run: handleSearch } = useDebounceFn(async (val) => {
    const resp = await getUserList({
      keyword: val,
    });

    const options = resp?.data?.list?.map((item) => {
      return {
        label: item.username,
        value: item.id,
      };
    });

    setUserOptions(options);
  }, 500);

  const discountByVal = (val) => {
    console.log('[editParams]', editParams);
    const discount = tradeDetail?.payment?.originAmount * (val / 10);
    console.log('[discount]', discount);
    editOrderForm.setFieldsValue({ totalAmount: discount?.toFixed(2) });
    setEditParams({ ...editParams, totalAmount: discount });
  };

  const discountByVal2 = (val) => {
    console.log('[editParams]', editParams);
    let discount = singEditParams?.totalAmount * (val / 10);
    console.log('[discount]', discount);
    discount = Number(Number(discount).toFixed(2));
    editSingleOrderForm.setFieldsValue({ totalAmount: discount?.toFixed(2) });
    setSingleEditParams({ ...singEditParams, totalAmount: discount });
  };

  return (
    <>
      <AddOrderProductModal
        visible={orderProductOpen}
        onClose={() => setOrderProductOpen(false)}
        onOk={async (vals) => {
          await handleEditOrder(
            [...makeTradeOrderList(tradeDetail?.orders), ...vals],
            vals?.length,
          );
        }}
      ></AddOrderProductModal>

      <Modal
        title="单件修改"
        zIndex={102}
        open={singleEditOpen}
        onOk={async () => {
          console.log('singEditParams', singEditParams);
          let finalParams = makeTradeOrderList(tradeDetail?.orders);
          finalParams = finalParams.map((item) => {
            if (item.orderId === singEditParams.orderId) {
              return {
                ...item,
                price: singEditParams.totalAmount,
              };
            }
            return item;
          });
          console.log('[finalParams]', finalParams);

          await handleEditOrder(finalParams);
          setSingleEditOpen(false);
        }}
        onCancel={() => {
          setSingleEditOpen(false);
          setSingleEditParams({});
          setCheckoutbindedUser(null);
          editSingleOrderForm.resetFields();
        }}
        destroyOnClose
      >
        <Card>
          <Form
            form={editSingleOrderForm}
            onValuesChange={(_, values) => {
              console.log('[_,values]', _, values);
              setSingleEditParams(values);
            }}
            initialValues={singEditParams}
          >
            <Card>
              <div className="">
                折扣：
                <InputNumber
                  placeholder="输入折扣自动计算"
                  style={{ width: '150px' }}
                  onChange={discountByVal2}
                ></InputNumber>
                <Row className="mt10" gutter={[10, 10]}>
                  <Col>
                    <Button onClick={() => discountByVal2(6)}>6折</Button>
                  </Col>
                  <Col>
                    <Button onClick={() => discountByVal2(8)}>8折</Button>
                  </Col>
                  <Col>
                    <Button onClick={() => discountByVal2(8.8)}>8.8折</Button>
                  </Col>
                  <Col>
                    <Button onClick={() => discountByVal2(9)}>9折</Button>
                  </Col>
                </Row>
              </div>

              <Form.Item
                className="mt10"
                label="金额"
                name={'totalAmount'}
                rules={[{ required: true }]}
              >
                <InputNumber></InputNumber>
              </Form.Item>
            </Card>
          </Form>
        </Card>
      </Modal>

      <Modal
        title="修改"
        zIndex={102}
        open={editOpen}
        onOk={() => {
          handleEditOrder();
          setEditOpen(false);
        }}
        onCancel={() => {
          setEditOpen(false);
          setEditParams({});
          setCheckoutbindedUser(null);
          editOrderForm.resetFields();
        }}
        destroyOnClose
      >
        <Card>
          <Form
            form={editOrderForm}
            onValuesChange={(_, values) => {
              console.log('[_,values]', _, values);
              setEditParams(values);
            }}
            initialValues={editParams}
          >
            <Form.Item label="人数" name="seat">
              <InputNumber></InputNumber>
            </Form.Item>
            <Form.Item
              label="桌号"
              name="tableId"
              rules={[{ required: true, message: '请选择桌号' }]}
            >
              <Select>
                {tableList.map((item) => (
                  <Option key={item.id} value={item.id}>
                    {item.name}
                  </Option>
                ))}
              </Select>
            </Form.Item>
            <Card>
              <div className="">
                折扣：
                <InputNumber
                  placeholder="输入折扣自动计算"
                  style={{ width: '150px' }}
                  onChange={discountByVal}
                ></InputNumber>
                <Row className="mt10" gutter={[10, 10]}>
                  <Col>
                    <Button onClick={() => discountByVal(6)}>6折</Button>
                  </Col>
                  <Col>
                    <Button onClick={() => discountByVal(8)}>8折</Button>
                  </Col>
                  <Col>
                    <Button onClick={() => discountByVal(8.8)}>8.8折</Button>
                  </Col>
                  <Col>
                    <Button onClick={() => discountByVal(9)}>9折</Button>
                  </Col>
                </Row>
              </div>

              <Form.Item
                className="mt10"
                label="金额"
                name={'totalAmount'}
                rules={[{ required: true }]}
              >
                <InputNumber></InputNumber>
              </Form.Item>
            </Card>
          </Form>
        </Card>
      </Modal>

      <Modal
        title="结账"
        open={checkoutModalOpen}
        onOk={handleCheckout}
        onCancel={() => {
          setCheckoutModalOpen(false);
        }}
        zIndex={101}
      >
        <Card title="会员信息">
          <div className="flex">
            <AutoComplete
              placeholder="请输入会员手机号搜索"
              className="w100"
              onChange={(v) => {
                setMenberInputVal(v);
                handleSearch(v);
              }}
              options={userOptions}
              onSelect={(id) => {
                getMenber(id);
              }}
              value={menberInputVal}
            ></AutoComplete>
            {/* <Button type="primary" className="ml10" onClick={searchMenber}>
              搜索
            </Button> */}
            {checkoutUser && (
              <Button type="primary" className="ml10" onClick={bindMenber}>
                绑定
              </Button>
            )}
          </div>

          {checkoutUser && (
            <Row className="mt20">
              <Col span={24}>
                <Row justify="space-between">
                  <Col>余额：</Col>
                  <Col>￥{checkoutUser?.balance}</Col>
                </Row>
                <Row justify="space-between" className="mt10">
                  <Col>积分</Col>
                  <Col>{checkoutUser?.credit}</Col>
                </Row>
              </Col>

              <Form
                form={menberForm}
                className="mt20"
                layout="vertical"
                onValuesChange={handlePreviewCheckout}
              >
                {!checkoutBindedUser && (
                  <div className="red mb10">* 请绑定会员后再进行下面操作</div>
                )}

                <Form.Item label="使用会员余额抵扣" name="useBalance">
                  <Switch disabled={!checkoutBindedUser}></Switch>
                </Form.Item>
                <Form.Item label="使用会员积分抵扣" name="useCredit">
                  <Switch disabled={!checkoutBindedUser}></Switch>
                </Form.Item>
              </Form>
            </Row>
          )}

          {!checkoutUser && <Empty className="mt20" description="可输入手机号确认会员" />}
        </Card>

        {/* <Card title="订单折扣" className="mt20">
          <Form layout="vertical">
            <Form.Item label="使用会员积分抵扣">
              <Switch></Switch>
            </Form.Item>
            <Form.Item label="使用会员余额抵扣">
              <Switch></Switch>
            </Form.Item>
          </Form>
        </Card> */}

        <Row className="mt20">
          <Col span={24}>
            {checkoutDetail && (
              <div>
                {/* <Row justify="space-between">
                  <Col>折扣列表：</Col>
                </Row> */}
                <Row justify="space-between">
                  <Col>余额抵扣：</Col>
                  <Col>￥{checkoutDetail?.balanceDeduction}</Col>
                </Row>
                <Row justify="space-between">
                  <Col>积分抵扣：</Col>
                  <Col>￥{checkoutDetail?.creditDeduction}</Col>
                </Row>
                <Row justify="space-between">
                  <Col>合计抵扣：</Col>
                  <Col>￥{checkoutDetail?.totalDeduction}</Col>
                </Row>
                <Divider></Divider>
              </div>
            )}
            <Row justify="space-between">
              <Col>总计金额：</Col>
              <Col>
                ￥
                {checkoutDetail?.amount !== undefined
                  ? checkoutDetail?.amount
                  : tradeDetail?.payment?.amount}
              </Col>
            </Row>
          </Col>
        </Row>
      </Modal>

      <Modal
        title={name}
        visible={open}
        onCancel={() => {
          if (loading) return;
          setOpen(false);
          setTradeDetail({});
          if (onCancel) {
            onCancel();
          }
        }}
        width={'80vw'}
        footer={null}
        zIndex={100}
        centered
        destroyOnClose
      >
        <Spin spinning={loading}>
          <Row gutter={[20, 20]}>
            <Col span={6}>
              <Card title="基础信息">
                <Row>订单号： {tradeDetail?.no}</Row>
                <Row className="mt10">开始就餐时间： {tradeDetail?.createdAt}</Row>
                {/* <Row className="mt10">人数： -</Row> */}
                <Row className="mt10">桌号： {tradeDetail?.restaurantTable?.name || '暂无'}</Row>
                <Row className="mt10">备注： {tradeDetail?.remark || '暂无'}</Row>
              </Card>
              <Card title="操作" className="mt20">
                <Row gutter={[0, 20]}>
                  {tradeDetail?.status === 1 && (
                    <Col span={24}>
                      <Button
                        danger
                        type="primary"
                        block
                        onClick={() => {
                          console.log('[tradeDetail]', tradeDetail?.payment?.originAmount);
                          editOrderForm.resetFields();
                          editOrderForm.setFieldsValue({
                            seat: tradeDetail?.seat,
                            tableId: tradeDetail?.restaurantTable?.id,
                            totalAmount: tradeDetail?.payment?.originAmount,
                          });
                          setEditParams({
                            seat: tradeDetail?.seat,
                            tableId: tradeDetail?.restaurantTable?.id,
                            totalAmount: tradeDetail?.payment?.originAmount,
                          });
                          setEditOpen(true);
                        }}
                      >
                        修改（折扣等）
                      </Button>
                    </Col>
                  )}
                  {tradeDetail?.status === 1 && (
                    <Col span={24}>
                      <Button
                        danger
                        type="primary"
                        block
                        onClick={() => setCheckoutModalOpen(true)}
                      >
                        结账（线下完单）
                      </Button>
                    </Col>
                  )}
                  {/* <Col span={24}>
                  <Button danger type="primary" block>
                    退单（取消）
                  </Button>
                </Col> */}
                  {tradeDetail?.status === 1 && (
                    <Col span={24}>
                      <Popconfirm
                        title="确认清台吗"
                        key="delete"
                        onConfirm={async () => {
                          const resp = await cancelTrade(orderId);

                          if (resp.code === 0) {
                            message.success('操作成功');
                            init();
                          }
                        }}
                      >
                        <Button danger type="primary" block>
                          清台（重置）
                        </Button>
                      </Popconfirm>
                    </Col>
                  )}
                  {tradeDetail?.status === 1 && (
                    <Col span={24}>
                      <Button
                        type="primary"
                        block
                        onClick={() => {
                          setOrderProductOpen(true);
                        }}
                      >
                        加单
                      </Button>
                    </Col>
                  )}
                  {tradeDetail?.status === 1 && (
                    <Col span={24}>
                      <Button
                        type="primary"
                        block
                        onClick={async () => {
                          const resp = await printTradeTicket(orderId);
                          if (resp.code === 0) {
                            message.success('操作成功');
                            init();
                          }
                        }}
                      >
                        打印制作分单
                      </Button>
                    </Col>
                  )}
                  <Col span={24}>
                    <Button
                      type="primary"
                      block
                      onClick={async () => {
                        const resp = await printCashierTicket(orderId);
                        if (resp.code === 0) {
                          message.success('操作成功');
                          init();
                        }
                      }}
                    >
                      打印结账单
                    </Button>
                  </Col>
                </Row>
              </Card>
            </Col>

            <Col span={18}>
              <Card title="订单详情">
                <Row>
                  <Col span={24}>
                    <Card title="价格">
                      <Row justify="space-between">
                        <Col>原价：</Col>
                        <Col>￥{tradeDetail?.payment?.originAmount}</Col>
                      </Row>
                      <Row justify="space-between">
                        <Col>调整：</Col>
                        <Col>￥{tradeDetail?.payment?.adjust}</Col>
                      </Row>
                      <Row justify="space-between">
                        <Col>折扣：</Col>
                        <Col>￥{tradeDetail?.payment?.discount}</Col>
                      </Row>
                      <Row justify="space-between red">
                        <Col>实际支付：</Col>
                        <Col>￥{tradeDetail?.payment?.amount}</Col>
                      </Row>
                    </Card>

                    <Row justify="space-between" className="mt10">
                      <Col>操作员：</Col>
                      <Col>-</Col>
                    </Row>
                    <Row justify="space-between" className="mt10">
                      <Col>创建时间：</Col>
                      <Col>{tradeDetail?.createdAt}</Col>
                    </Row>

                    <Row justify="space-between" className="mt10">
                      <Col>修改时间</Col>
                      <Col>{tradeDetail?.updatedAt}</Col>
                    </Row>
                    <Row justify="space-between" className="mt10">
                      <Col>状态：</Col>
                      <Col>
                        <OrderStatusTag status={tradeDetail?.status}></OrderStatusTag>{' '}
                      </Col>
                    </Row>
                  </Col>
                </Row>

                <Form form={productListForm} component={false}>
                  <Table
                    columns={mergedColumns}
                    dataSource={tradeDetail?.orders}
                    pagination={false}
                    className="mt10"
                    components={{
                      body: { cell: EditableCell },
                    }}
                  />
                </Form>
              </Card>
            </Col>
          </Row>
        </Spin>
      </Modal>
    </>
  );
};

export default OrderDetailModal;
